import requests
import time
from lxml import etree

class Ksw:
    "00ksw.org 操作类"

    # 以get方式请求网页
    def request(url):
        try:
            req = requests.get(url)
            req.encoding = "UTF-8"
            return req.text
        except:
            return ""


    # 获取页面内容
    def getcontent(url):
        ele     = etree.HTML(Ksw.request(url))
        time.sleep(0.1)
        judge = ele.xpath('/html/body/text()')
        if (judge[6] != '  \r\n无数据'):
            code = ele.xpath('/html/body/div[3]/div/div/div[1]/table/tbody/tr[1]/td[2]/text()[1]')
            cn_describe = ele.xpath('/html/body/div[3]/div/div/div[1]/table/tbody/tr[2]/td[2]/text()')
            en_describe = ele.xpath('/html/body/div[3]/div/div/div[1]/table/tbody/tr[3]/td[2]/text()')
            elements = ele.xpath('/html/body/div[3]/div/div/div[1]/table/tbody/tr[4]/td[2]/text()')
            example = ele.xpath('/html/body/div[3]/div/div/div[4]/table/tbody/tr[2]/td[3]/text()')
            if example:
                pass
            else:
                example.append("无实例")
            return {
                    "code" : int(code[0].split()[0]),
                    "cn_describe" : cn_describe[0],
                    "en_describe" : en_describe[0],
                    "elements" : elements[0],
                    "example" : example[0]

                }
        else:
            return "no"
